<template>
    <div class="permission-manage">
        <el-card>
            <template #header>
                <div class="header-bar">
                    <span>权限管理</span>
                    <div>
                        <el-button type="primary" size="small" @click="onAddPermission">新增权限</el-button>
                    </div>
                </div>
            </template>
            <el-table :data="tableData" row-key="id" border style="width: 100%; margin-bottom: 16px;">
                <el-table-column prop="permissionName" label="权限名" min-width="180">
                    <template #default="{ row }">
                        <span :class="{ 'no-data': !row.permissionName }">{{ row.permissionName || '暂无' }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="createdAt" label="创建时间" min-width="160">
                    <template #default="{ row }">
                        <span>{{ formatDate(row.createdAt) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="updatedAt" label="更新时间" min-width="160">
                    <template #default="{ row }">
                        <span>{{ formatDate(row.updatedAt) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="isActived" label="状态" min-width="80">
                    <template #default="{ row }">
                        <el-tooltip :content="row.isActived ? '点击禁用' : '点击激活'" placement="top">
                            <el-tag :type="row.isActived ? 'success' : 'warning'" style="cursor: pointer"
                                @click="onToggleStatus(row)">
                                {{ row.isActived ? '已激活' : '未激活' }}
                            </el-tag>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column label="操作" min-width="120">
                    <template #default>
                        <el-button type="danger" size="small" disabled>删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-bar">
                <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total"
                    :page-size="pageSize" :current-page="pageIndex" :page-sizes="[5, 10, 20, 50, 100]"
                    @size-change="handleSizeChange" @current-change="handlePageChange" />
            </div>
        </el-card>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { permissionApi } from '../api/permission'
const permissionStatusMap = ref({})
async function fetchPermissionStatus() {
    const res = await permissionApi.getPermissions(1, 1000)
    if (res.data.code === 1000) {
        permissionStatusMap.value = Object.fromEntries(
            res.data.data.items.map(perm => [perm.permissionName, perm.isActived])
        )
    }
}

const tableData = ref([])
const total = ref(0)
const pageIndex = ref(1)
const pageSize = ref(10)
const loading = ref(false)

function formatDate(date) {
    if (!date) return ''
    return new Date(date).toLocaleString()
}

async function fetchData() {
    loading.value = true
    try {
        const res = await permissionApi.getPermissions(pageIndex.value, pageSize.value)
        if (res.data.code === 1000) {
            tableData.value = res.data.data.items
            total.value = res.data.data.totalCount
        } else {
            ElMessage.error(res.data.msg || '获取权限数据失败')
        }
    } catch {
        ElMessage.error('获取权限数据失败')
    } finally {
        loading.value = false
    }
}

function handleSizeChange(val) {
    pageSize.value = val
    pageIndex.value = 1
    fetchData()
}

function handlePageChange(val) {
    pageIndex.value = val
    fetchData()
}

function onAddPermission() {
    ElMessage.info('新增权限功能待实现')
}

async function onToggleStatus(row) {
    try {
        let res
        if (row.isActived) {
            res = await permissionApi.disablePermission(row.id)
        } else {
            res = await permissionApi.enablePermission(row.id)
        }
        if (res.data.code === 1000) {
            ElMessage.success(res.data.msg || '操作成功')
            // 操作成功后强制刷新表格和权限状态映射
            await fetchData()
            await fetchPermissionStatus()
        } else {
            ElMessage.error(res.data.msg || '操作失败')
        }
    } catch {
        ElMessage.error('操作失败')
    }
}

onMounted(() => {
    fetchPermissionStatus()
    fetchData()
})
</script>

<style scoped>
.permission-manage {
    max-width: 1200px;
    margin: 20px auto;
}

.header-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.no-data {
    color: #c0c4cc;
    font-style: italic;
}

.pagination-bar {
    margin-top: 16px;
    text-align: right;
}
</style>